package com.demo.chat.controller;
/*
 *ClassName:ChatController
 *Description:
 *@author:可爱的大鸭子
 */

import com.demo.chat.Application;
import com.demo.chat.dao.MessageDao;
import com.demo.chat.pojo.SocketMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private MessageDao messageDao;

    @MessageMapping("/send")
    public void send(SocketMessage message) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        message.setDate(df.format(new Date()));
        String sessionId= Application.sessionMap.get(message.getToUser());  //要发送给的用户
        System.out.println("sessionId:"+sessionId);
        messagingTemplate.convertAndSendToUser(sessionId,"/topic/send",message,createHeaders(sessionId));
        //从这开始调serivice
        //messageDao.save(message);
    }

    private MessageHeaders createHeaders(String sessionId) {
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        System.out.println("headers:"+headerAccessor.getMessageHeaders());
        return headerAccessor.getMessageHeaders();
    }
}
